/**
 * 
 */
package com.rocky.project.util;

import java.util.Collection;
import java.util.Iterator;

import com.rocky.project.model.admin.Resource;
import com.rocky.project.model.admin.Role;
import com.rocky.project.model.admin.User;
import com.rocky.project.model.family.Archive;
import com.rocky.project.service.BaseService;




/**
 * @author new
 *
 */
public  class WebHelper {	
	
	private BaseService baseService;
	
	public BaseService getBaseService() {
		return baseService;
	}
	
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}
	
	@SuppressWarnings("unchecked")
	public Archive getLatestArchiveByFamilyid(Long familyid){		
		Collection pageRecords = baseService.executeHqlNoParam("select m  from  Archive m where  m.deleted = false and m.latest = true and m.family.id = "+familyid, 0, null);
		for(Iterator<Archive> iter = pageRecords.iterator();iter.hasNext();){			
			Archive archive = iter.next();
			return archive;
		}
		return new Archive();
	}
	
	public boolean haspermission(Resource resource){
		if(resource.isActive()&&resource.getStatus()!=null&&!resource.getStatus().equals("deprecated")){
			User user = WebUtil.getSessionUser();
			if(user.getUsername().equals("admin")){
				return true;
			}
			String roleId = getRoleidByMemberid(user.getId());
			String queryHql = "SELECT m FROM RoleResourceR  AS m WHERE m.deleted = false and m.resource.id='"+resource.getId()+"'  and m.role.id = '"+Long.valueOf(roleId)+"'";	
			Collection res = baseService.executeHqlNoParam(queryHql, 0, null);
			return res.isEmpty()?false:true;
		}		
		return false;
	}	
	
	private String  getRoleidByMemberid(Long id){		
		String queryHql = "SELECT m.role FROM UserRoleR AS m WHERE m.deleted = false and m.user.id='"+id+"'";	
		Collection res = baseService.executeHqlNoParam(queryHql, 0, null);
		return res.isEmpty()?"-1":((Role) res.iterator().next()).getId().toString();
	}
	
	public WebHelper() {		
	}
}
